package com.powernode.common.handle;

import com.powernode.common.constant.JWTConstants;
import com.powernode.common.model.R;
import com.powernode.common.model.SecurityUsers;
import com.powernode.common.utils.JwtUtils;
import com.powernode.common.utils.ResponseUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.Duration;

@Component
public class AppLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获取安全用户
        SecurityUsers securityUsers = (SecurityUsers)authentication.getPrincipal();
        //创建token
        String token = JwtUtils.createJwt(securityUsers);
        //将token放入redis中设置失效时间
        stringRedisTemplate.opsForValue().set(JWTConstants.JWT_REDIS_TOKEn+token,"", Duration.ofMillis(60*60*12L));
        //返回数据
        ResponseUtil.WriteJson(response, R.OK(token));
    }
}
